<template>
  <div class="app-container home" style="background-color: #eeeeee;">
    <!-- 头部 -->
    <el-row>
      <el-col :span="24">
        <div style="background-color: #ffffff;height: 100px;">
          <div style="padding: 10px;">
            <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
            <!-- <el-button type="primary" plain size="mini" @click="">导入</el-button> -->
            <el-button type="" plain size="mini" @click="delSelection" :disabled="roles == 'common'">删除</el-button>
          </div>
          <div class="div1">
            <el-radio-group v-model="queryParams.useStatus" @change="getList()">
              <el-radio-button label="0">全部</el-radio-button>
              <el-radio-button label="4">闲置</el-radio-button>
              <el-radio-button label="100">在用</el-radio-button>
              <el-radio-button label="101">借用</el-radio-button>
            </el-radio-group>
          </div>
          <p style="margin-top: -40px;margin-left: 300px;">
            <el-input placeholder="资产名称" clearable style="width: 240px" @keyup.enter.native=""
              v-model="queryParams.assetName" /> &nbsp;&nbsp;
            <el-button type="primary" icon="el-icon-search" size="mini" @click="" style="height: 34px;"
              @click="getList()">查询</el-button>
          </p>
        </div>
      </el-col>
    </el-row>

    <el-row>
      <el-col :span="24">
        <div style="margin-top: 10px;">
          <el-table :data="assetList" border v-loading="loading" @selection-change="delSelectionChange">
            <el-table-column type="selection" width="50" align="center" />
            <el-table-column label="资产名称" align="center" key="assetName" prop="assetName"></el-table-column>
            <el-table-column label="使用状态" align="center" key="statusName" prop="statusName" />
            <el-table-column label="资产类型" align="center" key="typeName" prop="typeName" />
            <el-table-column label="使用部门" align="center" key="deptName" prop="deptName" />
            <el-table-column label="使用人员" align="center" key="useName" prop="useName" />
            <el-table-column label="存放位置" align="center" key="zfwy" prop="locationName" />
            <el-table-column label="领/借用时间" align="center" key="date" prop="date" />
            <el-table-column label="操作" align="center" width="160" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-button size="mini" type="text" @click="editBtn(scope.row)">编辑</el-button>
                <el-button size="mini" type="text" @click="delAssetById(scope.row.assetId)"
                  :disabled="roles == 'common'">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize" @pagination="getList" class="custom-pagination" />
        </div>
      </el-col>
    </el-row>


    <!-- 添加或修改用户配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="750px" append-to-body>
      <el-form ref="form" :model="EamAsset" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="资产名称" prop="assetName">
              <el-input placeholder="请输入" maxlength="30" style="width: 400px;" v-model="EamAsset.assetName"
                show-word-limit />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="资产类型" prop="typeId">
              <el-select placeholder="请选择" style="width: 400px;" v-model="EamAsset.typeId">
                <el-option v-for="item in typeList" :key="item.typeId" :label="item.typeName"
                  :value="item.typeId"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="使用状态" prop="useStatus">
              <el-select placeholder="请选择" v-model="EamAsset.useStatus" @change="useStatusChange">
                <el-option v-for="item in dictDataList" :key="item.dictCode" :label="item.dictLabel"
                  :value="item.dictCode"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="存放位置" prop="locationId">
              <el-select placeholder="请选择" value="请选择" v-model="EamAsset.locationId">
                <el-option v-for="item in locationList" :key="item.locationId" :label="item.locationName"
                  :value="item.locationId"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="11">
            <el-form-item label="规格" prop="asseSpec">
              <el-input placeholder="请输入" maxlength="30" style="width: 220px;" v-model="EamAsset.asseSpec" />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="型号" style="margin-left: 30px;" prop="model">
              <el-input placeholder="请输入" maxlength="30" v-model="EamAsset.model" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="11">
            <el-form-item label="资产金额" prop="price">
              <el-input type="number" placeholder="请输入(元)" style="width: 220px;" v-model="EamAsset.price" />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="资产单位" style="margin-left: 30px;" prop="assetUnit">
              <el-input placeholder="请输入" v-model="EamAsset.assetUnit" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="购买日期" prop="buyTime">
              <el-date-picker type="date" placeholder="选择日期" v-model="EamAsset.buyTime" value-format="yyyy-MM-dd">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="过保日期" prop="expirationDate">
              <el-date-picker type="date" placeholder="选择日期" v-model="EamAsset.expirationDate"
                value-format="yyyy-MM-dd">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="报废日期" prop="scrapTime">
              <el-date-picker type="date" placeholder="选择日期" v-model="EamAsset.scrapTime" value-format="yyyy-MM-dd">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="资产用途">
              <el-input placeholder="请输入" maxlength="30" v-model="EamAsset.assetUse" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="资产编码">
              <el-input placeholder="请输入" maxlength="30" v-model="EamAsset.assetCode" style="width: 170px;"
                :disabled="authCode" />&nbsp;
              <el-checkbox v-model="authCode" :disabled="authCodeCheck">自动编码</el-checkbox>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="资产数量" prop="assetNum">
              <el-input-number placeholder="请输入" maxlength="30" style="width: 170px;"
                v-model="EamAsset.assetNum" />&nbsp;
              <!-- <el-checkbox v-model="checked2">批量新增</el-checkbox> -->
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="供应商" prop="supplierId">
              <el-select placeholder="请选择" value="请选择" style="width: 220px;" v-model="EamAsset.supplierId">
                <el-option v-for="item in supplierList" :key="item.supplierId" :label="item.supplierName"
                  :value="item.supplierId"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="发票号" prop="billNum">
              <el-input placeholder="请输入" maxlength="30" v-model="EamAsset.billNum" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="开票日期" prop="billTime">
              <el-date-picker type="date" placeholder="选择日期" v-model="EamAsset.billTime" value-format="yyyy-MM-dd">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="经办人" prop="nickName">
              <el-select placeholder="请选择" size="mini" value="请选择" style="width: 150px;" v-model="stock.handlePerson"
                :disabled="!storageChecked">
                <el-option v-for="item in userList" :key="item.userId" :label="item.nickName"
                  :value="item.userId"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="10" v-if="!isInsertAndUpdate">
            <el-form-item label="创建时间">
              <el-input v-model="EamAsset.createTime" :disabled="true"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row v-if="isImage == 1">
          <el-col :span="24">
            <el-form-item label="资产图片:">
              <span>图片支持jpg.png.gif格式，单个图片大小最大为20M。最多上传10张图片</span>
              <el-upload action="#" ref="upload" list-type="picture-card" :auth-upload="false"
                :on-preview="handlePictureCardPreview" :on-remove="handleRemove" :http-request="uploadAvatar"
                :before-upload="beforeAvatarUpload" :file-list="fileList">
                <i class="el-icon-plus"></i>
              </el-upload>

              <el-dialog :visible.sync="dialogVisible">
                <img width="100%" :src="dialogImageUrl" alt="">
              </el-dialog>
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-checkbox :disabled="stokChecked" v-model="storageChecked" style="margin-right: 30px;">入库</el-checkbox>
        <el-button type="primary" @click="getInsertAndUpdate">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


  </div>
</template>

<script>
  import axios from 'axios';
  import {
    getEamList,
    getTypeList,
    getLocationList,
    addEam,
    uploadImage,
    delAsset,
    addStock,
    updateEam,
    getInfoEam
  } from "@/api/eam-xl/index";
  import {
    getInfo
  } from "@/api/login";
  export default {
    name: '',
    data() {
      return {
        key: '',
        //文件上传用
        dialogImageUrl: '',
        dialogVisible: false,
        fileList: [],
        //自动编码
        authCode: true,
        //是否批量新增默认false
        checked2: false,
        // 遮罩层
        loading: true,
        // 总条数
        total: 0,
        // 弹出层标题
        title: "",
        // 部门树选项
        deptOptions: undefined,
        // 是否显示弹出层
        open: false,
        // 表单参数
        form: {},
        defaultProps: {
          children: "children",
          label: "label"
        },
        rules: {
          assetName: [{
            required: true,
            message: "用户名称不能为空",
            trigger: "blur"
          }, ],
          typeId: [{
            required: true,
            message: "请选择资产类型",
            trigger: "change"
          }, ],
          useStatus: [{
            required: true,
            message: "请选择使用状态",
            trigger: "change"
          }, ],
          locationId: [{
            required: true,
            message: "请选择存放位置",
            trigger: "change"
          }, ],
          asseSpec: [{
            required: true,
            message: "规格不能为空",
            trigger: "blur"
          }, ],
          model: [{
            required: true,
            message: "型号不能为空",
            trigger: "blur"
          }, ],
          price: [{
            required: true,
            message: "请输入金额",
            trigger: "blur"
          }, ],
          model: [{
            required: true,
            message: "型号不能为空",
            trigger: "blur"
          }, ],
          assetUnit: [{
            required: true,
            message: "资产单位不能为空",
            trigger: "blur"
          }, ],
          buyTime: [{
            required: true,
            message: "购买日期不能为空",
            trigger: "blur"
          }, ],
          expirationDate: [{
            required: true,
            message: "过保日期不能为空",
            trigger: "blur"
          }, ],
          scrapTime: [{
            required: true,
            message: "报废日期不能为空",
            trigger: "blur"
          }, ],
          assetUse: [{
            required: true,
            message: "资产用途不能为空",
            trigger: "blur"
          }, ],
          assetNum: [{
            required: true,
            message: "数量不能为空",
            trigger: "blur"
          }, ],
          supplierId: [{
            required: true,
            message: "请选择供应商",
            trigger: "change"
          }, ],
          billNum: [{
            required: true,
            message: "请输入发票号",
            trigger: "blur"
          }, ],
          billTime: [{
            required: true,
            message: "开票日期不能为空",
            trigger: "blur"
          }, ]
        },
        assetList: [

        ],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          assetName: undefined,
          useStatus: 0,
        },
        typeList: [], //资产类型列表
        locationList: [], //存放位置列表
        dictDataList: [], //使用状态列表
        supplierList: [], //供应商列表
        userList: [], //经办人列表
        EamAsset: {
          supplierId: undefined,
          locationId: undefined,
          typeId: undefined,
          assetCode: undefined,
          assetName: undefined,
          assetImage: undefined,
          price: undefined,
          assetNum: undefined,
          asseSpec: undefined,
          buyTime: undefined,
          scrapTime: undefined,
          assetUse: undefined,
          billNum: undefined,
          billTime: undefined,
          model: undefined,
          creator: undefined,
          createTime: undefined,
          usePerson: undefined,
          useStatus: undefined,
          expirationDate: undefined,
          spec: undefined,
          assetUnit: undefined
        },
        files: [], //存放资产图片
        selectedRows: [], //多选删除
        storageChecked: false, //是否入库
        stock: { //入库对象
          handlePerson: undefined,
          creator: undefined
        },
        authCodeCheck: false, //自动编码复选框
        isInsertAndUpdate: true, //判断新增还是修改
        stokChecked: false, //入库复选按钮
        roles: undefined, //权限
        user: {},
        fileImages: [],
        isImage:1,
      }
    },
    components: {

    },
    props: [],
    created() {
      this.getList();
      this.getType();
      getInfo().then((res) => {
        this.user = res.user;
        this.roles = res.roles;
      })
    },
    mounted() {

    },
    methods: {
      /** 新增按钮操作 */
      handleAdd() {
        this.isImage = 1;
        this.reset();
        this.open = true;
        this.authCodeCheck = false;
        this.title = "新增资产";
        this.isInsertAndUpdate = true;
        //获取当前登录用户为创建人

        this.EamAsset.creator = this.user.userId;
        this.stock.creator = this.user.userId;
        this.roles = res.roles;

      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.$refs["form"].resetFields();
        this.reset();
      },
      // 表单重置
      reset() {
        this.EamAsset = {};
        this.files = [];
        this.storageChecked = false;
        this.stock.handlePerson = undefined;
        this.emptyUpload();
      },
      // 文件上传
      beforeAvatarUpload(file) {
        //上传限制
        const isJPG = file.type === 'image/jpeg'
        const isPng = file.type === 'image/png'
        const isGif = file.type === 'image/gif'
        const isLt2M = file.size / 1024 / 1024 < 20

        if (!isJPG && !isPng && !isGif) {
          this.$message.error('上传图片只能是 JPG、png、Gif 格式!')
        }
        if (!isLt2M) {
          this.$message.error('上传图片大小不能超过 20MB!')
        }
        this.fileImages.push(file);
        if (this.fileImages.length > 10) {
          this.$message.warning("最多上传10张图片")
          return false;
        }
        return (isJPG || isPng) && isLt2M
      },

      handleRemove(file, fileList) { //文件删除
        // 找到元素的索引
        let index = this.files.indexOf(file.raw);
        // 如果找到了元素，就使用splice删除它
        if (index != -1) {
          this.files.splice(index, 1);
        }
        // this.files.splice(file,1);
      },
      handlePictureCardPreview(file) { // 显示大图
        this.dialogImageUrl = file.url;
        this.dialogVisible = true;
      },
      uploadAvatar(item) {
        //自定义上传的实现
        this.files.push(item.file);
      },
      emptyUpload() {
        //清空上传组件
        console.log("----upload.clearFiles");
        const mainImg = this.$refs.upload
        if (mainImg) {
          if (mainImg.length) {
            mainImg.forEach(item => {
              item.clearFiles()
            })
          } else {
            this.$refs.upload.clearFiles()
          }
        }
      },
      //分页
      handleSizeChange(val) {
        console.log(`每页 ${val} 条`);
      },
      handleCurrentChange(val) {
        console.log(`当前页: ${val}`);
      },
      getList() {
        this.loading = true;;
        getEamList(this.queryParams).then((response) => {
          this.assetList = response.rows;;
          this.total = response.total;
          this.loading = false;
        })
      },
      getType() { //新增遮罩层打开调用,填充下拉列表数据
        getTypeList().then((res) => {
          this.typeList = res.typeList;
          this.locationList = res.locationList;
          this.dictDataList = res.dictDataList;
          this.supplierList = res.supplierList;
          this.userList = res.userList;
        })
      },

      getAddEam() { //新增确定按钮
        let _this = this;
        if (this.files.length == 0) {
          this.$message({
            message: '请添加资产图片',
            type: 'warning'
          });
        } else {
          if (!this.authCode) {
            if (this.EamAsset.assetCode == null) {
              this.$message.warning("请输入资产编码")
              return;
            }
          }
          this.$refs["form"].validate((valid) => {        //添加表单验证
            if (valid) {
              const formData = new FormData();
              _this.files.forEach((file, index) => {
                formData.append("files", file);
              });
              formData.append("assetId", 0); //判断新增还是修改
              formData.append("type", "null"); //判断新增还是修改
              //新增
              addEam(_this.EamAsset).then((res) => {

              }).then(() => { //入库
                if (_this.storageChecked) {
                  addStock(_this.stock).then((res)=>{
                    _this.$modal.msgSuccess(res.msg)
                  });;
                }
              }).then(() => { //上传图片
                uploadImage(formData).then(res => {
                  _this.$modal.msgSuccess("添加成功");
                  _this.cancel();
                  _this.open = false;
                  _this.loading = true;
                  _this.getList();
                })
              })
            }
          });

        }
      },

      delAssetById(assetId) { //删除按钮
        let _this = this;
        this.$modal.confirm('是否确认删除资产编号为"' + assetId + '"的数据项？').then(function() {
          _this.loading = true;
          delAsset(assetId).then((res) => {
            _this.$modal.msgSuccess("删除成功");
            _this.getList();
          })
        })
      },

      delSelectionChange(selection) { //多选删除将值存储到selectedRows集合中
        this.selectedRows = selection;
      },
      delSelection() { //多选删除按钮
        if (this.selectedRows.length == 0) {
          this.$message("请选择你要删除的资产");
        } else {
          let _this = this;
          this.$modal.confirm('是否删除已选项？').then(function() {
            _this.loading = true;
            let assetIds = [];
            _this.selectedRows.forEach((item, index) => {
              assetIds.push(item.assetId);
            })
            delAsset(assetIds).then((res) => {
              _this.$modal.msgSuccess(res.msg);
              _this.getList();
            })
          })
        }
      },

      editBtn(asset) { //编辑按钮
        this.isImage = 2;
        getInfoEam(asset.assetId).then(res=>{
          this.EamAsset = res.data;
          this.useStatusChange();
        })
        this.authCodeCheck = true;
        this.open = true;
        this.title = "编辑资产";
        this.isInsertAndUpdate = false;
        //获取当前登录用户为创建人
        getInfo().then((res) => {
          this.EamAsset.creator = res.user.userId;
          this.stock.creator = res.user.userId;
        })
      },

      getInsertAndUpdate() { //弹框确认按钮
        if (this.storageChecked) {
          if (this.stock.handlePerson == undefined) {
            this.$message("请选择经办人");
            return null;
          }
        }
        //判断是新增还是修改
        if (this.isInsertAndUpdate) { //新增
          this.getAddEam();
        } else { //修改

          this.getUpdateEam();
        }
      },


      getUpdateEam() { //编辑方法
        if (this.roles == "common") {
          this.$message.warning("您没有此权限");
          return;
        }
        let _this = this;
        this.$modal.confirm('确认修改"' + _this.EamAsset.assetCode + '"资产单号的数据？').then(function() {
          //修改
          updateEam(_this.EamAsset).then((res) => {
            if (res.msg == "操作成功") {
              _this.$modal.msgSuccess(res.msg)
              //上传图片
              if (_this.files.length != 0) {
                const formData = new FormData();
                _this.files.forEach((file, index) => {
                  formData.append("files", file);
                });
                formData.append("assetId", _this.EamAsset.assetId); //判断新增还是修改
                formData.append("type", "null");
                uploadImage(formData);
              } else if (_this.storageChecked) { //入库
                _this.stock.assetId = _this.EamAsset.assetId;
                addStock(_this.stock).then((res1) => {
                  _this.$modal.msgSuccess(res1.msg)
                });
              }
            }
            _this.cancel();
            _this.reset();
            _this.open = false;
            _this.loading = true;
            _this.getList();
          })
        })
      },

      useStatusChange() { //使用状态值改变事件
        if (this.EamAsset.useStatus == 4) {
          this.stokChecked = false;
        } else {
          this.stokChecked = true;
          this.storageChecked = false;
        }
      },
    }
  }
</script>

<style scoped>
  .div1 {
    width: 280px;
    height: 40px;
    border-radius: 3px;
    margin-left: 10px;
  }

  .div1 button {
    width: 25%;
    height: 100%;
    background-color: #ffffff;
    border: none;
    border-left: 1px solid #c8c8c8;

  }

  /* //文件上传 */
  .avatar-uploader {
    border: 2px dashed #d9d9d9;
    width: 180px;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;

  }

  .avatar-uploader:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }

  /*分页*/
  .custom-pagination {
    margin: 0px auto;
    height: 50px;
  }
</style>
